from utils.electrode_ctrl import ElectrodeCtrl
import numpy as np
from time import sleep, perf_counter
from utils import pressure_recv_svr

def sleep_us(us: float):
    sleep(us / 1_000_000)

# Function to busy-wait for a specified number of microseconds
def busy_wait_us(us: float):
    end_time = perf_counter() + us / 1_000_000  # Calculate end time in seconds
    while perf_counter() < end_time:
        pass  # Busy-wait loop

if __name__ == '__main__':
    frame_open = np.zeros((8, 8))
    board = ElectrodeCtrl('COM9', 115200, 'com')  # 2号板子（靠近风扇）
    pattern = np.zeros((8, 8))

    # 电压和阈值设定
    N_threshold = 350  # 压力传感器阈值
    PW_min = 200  # 小脉冲宽度，对应小电压感知
    PW_max = 1000  # 大脉冲宽度，对应大电压感知
    PW = PW_min
    PP_min=1000  #长脉冲周期，小脉冲频率，对应小电压感知
    PP_max=700  #短脉冲周期，大脉冲频率，对应大电压感知
    PP=PP_min
    previous_pressure_g = 0.0

    # 启动压力传感器服务器
    pressure_recv_svr.start_pressure_recv_svr(sensor_model='jn485', com_port='COM11', com_baud=38400)

    while True:
        pressure_g = pressure_recv_svr.global_data
        d_N = pressure_g - previous_pressure_g
        previous_pressure_g = pressure_g

        # 根据压力传感器的数值调整脉冲宽度
        if pressure_g < N_threshold:
            if d_N > 0:
                PW = PW_min
                PP = PP_min
            elif d_N < 0:
                PW = PW_max
                PP = PP_max
        else:
            PW = 0  # 设置为0可能表示无刺激，这取决于具体实现

        print(f'Detected Pressure: {pressure_g}, Pulse Width: {PW}')

        # 扫描电极的逻辑
        for column in range(8):
            count = 0
            print(f'第{column + 1}列，开始扫描，持续1s')
            start_time = perf_counter()  # Record the start time using perf_counter
            while perf_counter() - start_time < 0.07:  # 持续1秒钟
                for line in range(4, 6):  # index is 4 and 5 (5th and 6th row)
                    if line == 4:
                        pattern[line, column] = 1
                    if line == 5:
                        pattern[line, 7-column] = 1
                        print(pattern)

                    # 取消板子高阻态
                    board.on()
                    board.set_tick(pattern=pattern,
                                   pp=PP,
                                   pw=PW,  # 使用动态脉冲宽度
                                   pn=1,
                                   bp=1000,
                                   pulse_type='neg'
                                   )

                    tick_start_time = perf_counter()
                    busy_wait_us(1000)  # Busy-wait for 10 microseconds
                    tick_end_time = perf_counter()
                    board.off()

                    pattern.fill(0)
                count += 1
            print(f'第{line + 1}行 第{column + 1}列 扫描完毕')
            print(f'第{line + 1}行 第{column + 1}列 扫描次数：{count}')
